#include "pagelogmgmt.h"
#include "ui_pagelogmgmt.h"
#include "pageusermgmt.h"
#include "ui_pageusermgmt.h"
#include <QFileDialog>
#include <QDate>
#include <QDebug>

pageLogMgmt::pageLogMgmt(QWidget* parent)
    : QWidget(parent), ui(new Ui::pageLogMgmt), logManager(new LogManager(this)),
      logModel(new QStandardItemModel(this)) {
    ui->setupUi(this);

    // 初始化模型列（新增设备ID列）
    logModel->setColumnCount(7);
    logModel->setHorizontalHeaderLabels({"日志ID", "时间戳", "日志类型", "日志级别", "日志内容", "用户ID", "设备ID"});
    ui->logTableView->setModel(logModel);

    // 初始化时间控件
    ui->startTimeEdit->setDate(QDate::currentDate().addDays(-7));
    ui->endTimeEdit->setDate(QDate::currentDate());

    // 连接信号槽
    connect(ui->startTimeEdit, &QDateEdit::dateChanged, this, &pageLogMgmt::loadLogs);
    connect(ui->endTimeEdit, &QDateEdit::dateChanged, this, &pageLogMgmt::loadLogs);
    connect(ui->logTypeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &pageLogMgmt::loadLogs);
    connect(ui->refreshButton, &QPushButton::clicked, this, &pageLogMgmt::loadLogs);
    loadLogs();

    // 创建居中委托实例
    CenteredItemDelegate *centeredDelegate = new CenteredItemDelegate(this);
    for (int col = 0; col < logModel->columnCount(); ++col) {
        ui->logTableView->setItemDelegateForColumn(col, centeredDelegate);
    }

    // 自适应列宽
    ui->logTableView->resizeColumnsToContents();
    // 手动加宽特定列（单位：像素）
    ui->logTableView->setColumnWidth(1, 180);  // 时间戳列（第1列）设为180像素
    ui->logTableView->setColumnWidth(4, 300);  // 日志内容列（第4列）设为250像素
    ui->logTableView->setColumnWidth(2, 120);  // 日志类型列（第2列）设为120像素
}

pageLogMgmt::~pageLogMgmt() {
    delete ui;
}

void pageLogMgmt::loadLogs() {
    QDate startDate = ui->startTimeEdit->date();
    QDate endDate = ui->endTimeEdit->date();
    QString startTime = startDate.toString("yyyy-MM-dd") + " 00:00:00";
    QString endTime = endDate.toString("yyyy-MM-dd") + " 23:59:59";

    QString logType;
    switch(ui->logTypeCombo->currentIndex()) {
    case 1: logType = "SYSTEM"; break;
    case 2: logType = "OPERATION"; break;
    case 3: logType = "ALERT"; break;
    case 4: logType = "EXCEPTION"; break;
    default: logType = "";
    }

    logModel->removeRows(0, logModel->rowCount());
    qDebug() << "开始查询日志，开始时间: " << startTime << "，结束时间: " << endTime << "，日志类型: " << logType;
    QList<QSqlRecord> logs = logManager->queryLogs(startTime, endTime, logType);
    qDebug() << "查询到的日志记录数量: " << logs.size();

    for (const auto& log : logs) {
        QList<QStandardItem*> items;
        items << new QStandardItem(log.value("log_id").toString())
              << new QStandardItem(log.value("timestamp").toString())
              << new QStandardItem(log.value("log_type").toString())
              << new QStandardItem(log.value("log_level").toString())
              << new QStandardItem(log.value("content").toString())
              << new QStandardItem(log.value("user_id").toString())
              << new QStandardItem(log.value("device_id").toString());
        logModel->appendRow(items);
    }

    ui->logTableView->resizeColumnsToContents();
    // 手动加宽特定列（单位：像素）
    ui->logTableView->setColumnWidth(1, 180);  // 时间戳列（第1列）设为180像素
    ui->logTableView->setColumnWidth(4, 250);  // 日志内容列（第4列）设为250像素
    ui->logTableView->setColumnWidth(2, 120);  // 日志类型列（第2列）设为120像素
}

void pageLogMgmt::on_exportLogButton_clicked() {
    QString filter = "CSV Files (*.csv);;Text Files (*.txt)";
    QString filePath = QFileDialog::getSaveFileName(this, "Export Logs", "logs", filter);
    if (filePath.isEmpty()) {
        qDebug() << "用户取消了文件保存操作";
        return;
    }

    QDate startDate = ui->startTimeEdit->date();
    QDate endDate = ui->endTimeEdit->date();
    QString startTime = startDate.toString("yyyy-MM-dd") + " 00:00:00";
    QString endTime = endDate.toString("yyyy-MM-dd") + " 23:59:59";

    QString logType;
    switch(ui->logTypeCombo->currentIndex()) {
    case 1: logType = "SYSTEM"; break;
    case 2: logType = "OPERATION"; break;
    case 3: logType = "ALERT"; break;
    case 4: logType = "EXCEPTION"; break;
    default: logType = "";
    }

    qDebug() << "开始导出日志，文件路径: " << filePath << "，开始时间: " << startTime << "，结束时间: " << endTime << "，日志类型: " << logType;
    if (filePath.endsWith(".csv")) {
        logManager->exportLogsToCSV(filePath, startTime, endTime, logType);
    } else if (filePath.endsWith(".txt")) {
        logManager->exportLogsToText(filePath, startTime, endTime, logType);
    }
}
